var JJHH     = {"名称": "家家户户组件集合"};
JJHH.Http    = {"名称": "获取数据服务"};
JJHH.Dialog  = {"名称": "对话框组件"};
JJHH.Loading = {"名称": "加载动画"};

/*
*@todo  ( select )获取商户列表
*@param ( int )电话号
*/
JJHH.Http.getshopList = function (url, activity_id, callback) {
    $.ajax( {
       "url": url,
       "type": "POST",
       "dataType": "json",
       "data": {"data_type": 1, "activity_id": activity_id}
    } ).done(function( json ){
        callback( json );
    } );
}

/*
*@todo  ( add )绑定商户和活动
*@param ( int )电话号
*/
JJHH.Http.bindShop2Activity = function( url, opts, callback ){
    
    $.ajax({
       "url": url,
       "type": "POST",
       "dataType": "json",
       "data": {
                "activity_id": opts.activity_id, 
                "shop_id": opts.shop_id,
                "order_start_num": opts.order_start_num,
                "order_end_num": opts.order_end_num
               }
    }).done(function( json ){
        callback(json);
    });
}



/*
*@todo 现场收银_获取用户信息
*@param ( int )电话号
*/
JJHH.Dialog.getUserOne = function( mobile ){

    var json     = {"one": {"name": "张学友", "mobile": "1361355512"}};
    var tpl      = $( "#tpl_user_one" ).html();
    var template = _.template( tpl );
    var html     = template( json );  
    // 对话框
    var d = dialog( {
        "width": 320,
        "title": "用户信息",
        "okValue": "确 定",
        "ok": function () {
            dialog().close();
        }
    } );

    d.content( html );
    d.showModal();        
}

/*
*@todo 现场退款_获取订单信息
*@param ( int )电话号
*/
JJHH.Dialog.getOrderOne = function( order_id ){

    var json     = {"one": {"order_id": 1235551, "shanghu": "北京百度", "pinlei": "地板", "dianpu": "圣象地板"}};
    var tpl      = $( "#tpl_order_one" ).html();
    var template = _.template( tpl );
    var html     = template( json );   

    // 对话框
    var d = dialog( {
        "width": 320,
        "okValue": "绑 定",
        "title": "订单信息",
        "ok": function () {
            alert(1);
        }
    } ).showModal(); 

    d.content( html );
}
// JJHH.Dialog.xctk_hqddxx();

/*
*@todo 销售纸质订单
*@param ( string ) 商家列表接口
*@param ( string ) 绑定商家和活动接口
*/
JJHH.Dialog.bindShop2Activity = function( url_shop, url_bind ){
    // 表单数据
    var form_data = {};
    // 对话框
    var d = dialog( {
        "width": 360,
        "okValue": "绑 定",
        "title": "订单绑定",
        "ok": function () {
            form_data.activity_id      = $( "#j-activity-list" ).val();
            form_data.shop_id          = $( "#j-shop-list" ).val();
            form_data.order_start_num  = parseInt( $( "#j-start-order" ).val() );
            form_data.order_end_num    = parseInt( $( "#j-end-order" ).val() );
            if( 1 > form_data.activity_id ){
                dialog().content( "请选择\"活动\"" ).button( [{"value":"返回修改"}] ).showModal();
                return false;
            }else if( 1 > form_data.shop_id ){
                dialog().content( "\"参展店铺\"不能为空" ).button( [{"value":"返回修改"}] ).showModal();
                return false;
            }else if( 1 > form_data.order_start_num ){
                dialog().content( "请检查\"最小订单号\"" ).button( [{"value":"返回修改"}] ).showModal();
                return false;
            }else if( 1 > form_data.order_end_num ){
                dialog().content( "请检查\"最大订单号\"" ).button( [{"value":"返回修改"}] ).showModal();
                return false;
            }else if( form_data.order_start_num > form_data.order_end_num ){
                dialog().content( "\"最大订单号\"不能小于\"最小定单号\"" ).button( [{"value":"返回修改"}] ).showModal();
                return false;
            }else{
                var loading_dialog = dialog().title( "正在为您绑定数据..." ).showModal();
                JJHH.Http.bindShop2Activity( url_bind, form_data, function( json ){
                    loading_dialog.remove().close();
                    if( 1 == json.status ){
                        var d_success = dialog().content( "提交成功,3秒钟自动关闭!" ).button( [{"value":"关闭"}] ).showModal();
                        setTimeout( function(){
                            d.remove().close();
                            d_success.remove().close();
                        }, 2000 ); 
                        return false;
                    }else{
                        dialog().content( json.info ).button( [{"value":"返回"}] ).showModal();
                        return false;
                    }
                } );
            }
            return false;
        },
        "cancelValue": '取消',
        "cancel": function () {}
    } ).showModal();

    // 活动列表
    var html_activity_list = $( "#tpl_select_activity" ).html();

    // 获取活动列表 - 初始化阶段
    var activity_id = $( html_activity_list ).find("option").eq(0).val();
    JJHH.Http.getshopList( url_shop, activity_id, function( json ){
        if( 0 == json.status ){
            var html_shop_list = "<select id=\"j-shop-list\" class=\"form-control\"> <option value=\"0\">" + json.info + "</option></select>"; 
        }else{
            var tpl            = $( "#tpl_select_shop" ).html();
            var template       = _.template( tpl );
            var html_shop_list = template( json );    
        }

        var html = "<label>活动列表</label><div class=\"padding10\">" + html_activity_list + "</div>";
        html+= "<label>参展店铺</label><div class=\"padding10\">" + html_shop_list + "</div>";
        html+= "<div id=\"j-loading-warp\"></div>"; 
        html+= "<label>纸质订单编号范围</label><input onkeyup=\"value=value.replace(/[a-zA-z\.]+$/,'')\" id=\"j-start-order\" placeholder=\"最小订单号\" class=\"order_id n-auto-next \"/> <b>~</b> <input onkeyup=\"value=value.replace(/[a-zA-z\.]+$/,'')\" id=\"j-end-order\" placeholder=\"最大订单号\" class=\" n-auto-next order_id\"/>";
        
        // 对话框 - 填充
        d.content( html );
        $( "#j-shop-list" ).add( "#j-activity-list" ).css( "width", "100%").select2();
        $( ".n-auto-next" ).autoNext();
        // 获取活动列表 - change触发
        $( "#j-activity-list" ).change( function(){
        	var activity_id = $( this ).val();
        	$( "#j-shop-list" ).select2("destroy").hide();
        	// 执行加载动画
            var loading = dialog().content().showModal();
        	JJHH.Http.getshopList( url_shop, activity_id, function( json ){
                loading.close().remove();
        		if( 1 == json.status ){
        			// 有数据
        			var tpl            = $( "#tpl_select_shop" ).html();
			        var template       = _.template( tpl );
			        var html_shop_list = template( json ); 
        			$( "#j-shop-list" ).html( html_shop_list );
        			$( "#j-shop-list" ).select2();
        		}else{
        			// 无数据
        			$( "#j-shop-list" ).html( "<option value=\"0\">" + json.info + "</option>" );
        			$( "#j-shop-list" ).select2();
        		}
        		// d.content( html );  
        	} );
        } );
    } );
}


/*
*@todo 省/市/区/居民区4级联动
*@param {json}省数据
*@param {int}需要显示到层级
*@param {json}服务端接口
*@return 
*/
function jjhh_select_area(url_area, category_deep){

    // 初始化功能
    var $province        = $("#j-select-province");
    var $city            = $("#j-select-city");
    var $ward            = $("#j-select-ward");
    var $village         = $("#j-select-village");

    var province_default = $province.html();
    var city_default     = $city.html();
    var ward_default     = $ward.html();
    var village_default  = $village.html();

    //位置不能动, 内部读取了前面的变量
    function _reset_next_select(current_level){
        if( 1 == current_level ){
            if( "disabled" != $city.attr("disabled")){
                $city.html(city_default).attr("disabled", "disabled").select2();
            }
            if("disabled" != $ward.attr("disabled")){
                $ward.html(ward_default).attr("disabled", "disabled").select2();
            }   
            if("disabled" != $village.attr("disabled")){ 
                $village.html(village_default).attr("disabled", "disabled").select2();
            }    
        }
        if( 2 == current_level ){
            if("disabled" != $ward.attr("disabled")){
                $ward.html(ward_default).attr("disabled", "disabled").select2();
            }   
            if("disabled" != $village.attr("disabled")){ 
                $village.html(village_default).attr("disabled", "disabled").select2();
            }  
        }
        if( 3 == current_level ){
            if("disabled" != $village.attr("disabled")){ 
                $village.html(village_default).attr("disabled", "disabled").select2();
            }
        }
    }

    if (1 <= category_deep) {
        function _get_province_xhr(callback){
            $.ajax({
                "url": url_area.province,
                "type": "GET",
                "cache": true,
                "ifModified": true,
                "headers": {
        'Cache-Control': 'private', "Expires":"Thu, 19 Nov 2981 08:52:00 GMT" },
                "dataType": "JSON"
            }).done(function(json) {
                callback(json.data);
            });   
        }
        // 初始化样式
        $province.css("display", "block").select2();
        // 省
        _get_province_xhr(function(data){
            var html = "";
            var def = $province.data("default") || 0;
            for (k in data) {
                var selected = (def == data[k].province_id) ? "selected" : ""; 
                html+= "<option " + selected + " value=\"" + data[k].province_id + "\">" + data[k].province_name + "</option>";
            }
            $province
            .append(html)
            .prop("disabled", false)
            .select2();
        });            
    } 
    // 市模块
    if (2 <= category_deep) {
        var city_def = $city.data("default");
        $city.css("display", "block").select2();

        function _set_city_disabled(html) {
            var province_def = $province.data("default");
            var is_disabled = !(0 < province_def || 0 < city_def || $province.val() > 0);
            $city.prop("disabled", is_disabled).html(html).select2();  
        }
        // 城市数据
        // 默认城市id
        function _get_city_xhr(province_id, callback) {
            // 重置市select为为选择
            _reset_next_select(1);                    
            $.ajax({
                "url": url_area.city,
                "type": "GET",
                "dataType": "JSON",
                "data": {"province_id": province_id}
            }).done(function(json) {
                callback(json.data, $city.data("default"));
            });                    
        }
        
        // 初始化默认值
        if (0 <= city_def) {
            var province_id = $province.data("default");
            _get_city_xhr(province_id, function(data, city_def) {
                var html = city_default;
                for (k in data) {
                    var selected = (city_def == data[k].city_id) ? "selected" : ""; 
                    html += "<option " + selected + " value=\"" + data[k].city_id + "\">" + data[k].city_name + "</option>";
                }
                _set_city_disabled(html)
            });
        }
        // 省.change
        $province.change(function(){
            var province_id = $(this).val();
            _get_city_xhr(province_id, function(data) {
                var html = city_default;
                for (k in data) {
                    html += "<option value=\"" + data[k].city_id + "\">" + data[k].city_name + "</option>";
                }
                _set_city_disabled(html)
            });
        });
    }
    if (3 <= category_deep) {
        // 初始化标签样式
        var ward_def = $ward.data("default");
        $ward.css("display", "block").select2();

        function _set_ward_disabled(html) {
            var city_def = $city.data("default");
            var is_disabled = ! (0 < $city.data("default")|| 0 < ward_def || $city.val() > 0);
            $ward.prop("disabled", is_disabled).html(html).select2();  
        }
         
        function _get_ward_xhr(city_id, callback) {
            // 重置区select为为选择
            _reset_next_select(2);
            $.ajax({
                "url": url_area.ward,
                "type": "GET",
                "dataType": "JSON",
                "data": {"city_id": city_id}
            }).done(function(json) {
                var data = json.data;
                callback(data, $ward.data("default"));
            });
        }
       
        // 初始化默认值
        if (0 <= ward_def) {
            var city_def = $city.data("default");
            _get_ward_xhr(city_def, function(data, ward_def) {
                var html = ward_default;
                for (k in data) {
                    var selected = (ward_def == data[k].ward_id) ? "selected" : ""; 
                    html += "<option " + selected + " value=\"" + data[k].ward_id + "\">" + data[k].ward_name + "</option>";
                }
                _set_ward_disabled(html);                     
            })
        } 
        // 市.change

        $city.change(function() {
            var city_id = $(this).val();
            _get_ward_xhr(city_id, function(data) {
                var html = ward_default;
                for (k in data) {
                    html += "<option value=\"" + data[k].ward_id + "\">" + data[k].ward_name + "</option>";
                }
                _set_ward_disabled(html);
            });
        }); 
    }
    if (4 <= category_deep) {
        var village_def = $village.data("default");

        function _set_village_disabled(html) {
            var ward_def = $ward.data("default");
            var is_disabled = ! (0 < $ward.data("default")|| 0 < village_def || $ward.val() > 0);
            $village.prop("disabled", is_disabled).html(html).select2();  
        }

        function _get_village_xhr(ward_id, callback) {
            // 重置居民区select为为选择
            _reset_next_select(3);
            $.ajax({
                "url": url_area.village,
                "type": "GET",
                "dataType": "JSON",
                "data": {"ward_id": ward_id}
            }).done(function(json) {
                callback(json.data, $village.data("default"));
            });               
        }
        $village.select2();
        if (0 <= village_def) {
            var ward_def = $ward.data("default");
            _get_village_xhr(ward_def, function(data, def) {
                var html = village_default;
                for (k in data) {
                    var selected = (def == data[k].village_id) ? "selected" : ""; 
                    html += "<option " + selected + " value=\"" + data[k].village_id + "\">" + data[k].village_name + "</option>";
                }
                _set_village_disabled(html);
            });
        } 
        //区.change
        $ward.change(function() {
            var ward_id = $(this).val();
            _get_village_xhr(ward_id, function(data) {
                var html = village_default;
                for (k in data) {
                    html += "<option value=\"" + data[k].village_id + "\">" + data[k].village_name + "</option>";
                }
                _set_village_disabled(html);
            });
        }); 
    }
 
}